package com.atguigu.gulimall.product.controller;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import lombok.AllArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author ly
 */
@Controller
@AllArgsConstructor(onConstructor_ = @Autowired)
public class IndexController {

    private final CategoryService categoryService;

    private final RedissonClient redisson;

    private final StringRedisTemplate redisTemplate;

    @GetMapping({"/", "index.html"})
    public String indexPage(Model model) {
        //1、查出一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Category();
        model.addAttribute("categorys", categoryEntities);
        //视图解析器进行拼串:
        //classpath:/templates/+返回值+.html
        return "index";
    }

    /**
     * 测试获取菜单数据
     *
     * @return 菜单json
     */
    @ResponseBody
    @GetMapping("/index/json/catalog.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        return categoryService.getCatalogJson();
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //1、获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //2、加锁
        lock.lock();
        try {
            System.out.println("加锁成功，执行业务....." + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //3、解锁
            System.out.println("释放锁......" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    /**
     * 测试读写锁
     * 在写数据的时候，读操作只能等待，等到写操作完成之后才能读取到值
     * 修改期间，写锁是一个排它锁(互斥锁)，读锁是一个共享锁
     */
    @ResponseBody
    @GetMapping("/write")
    public String writeValue() {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        RLock writeLock = readWriteLock.writeLock();
        String s = "";
        try {
            // 1、改数据加写锁，读数加读锁
            writeLock.lock();
            System.out.println("写锁加锁成功……" + Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
            System.out.println("写锁释放");
        }
        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String readValue() {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        RLock readLock = readWriteLock.readLock();
        readLock.lock();
        String s = "";
        try {
            System.out.println("读锁加锁成功……" + Thread.currentThread().getId());
            s = redisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
            System.out.println("读锁释放");
        }
        return s;
    }

    /**
     * 测试信号量机制：
     * 车库停车，3个车位
     * 信号量也可以用作分布式限流
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        // 获取一个信号，即获取一个值，占一个车位
         park.acquire();
        // 上面是获取不到就一直阻塞式等待，直到等到位置，tryAcquire是尝试获取，获取不到就算了
        boolean b = park.tryAcquire();
        if (b) {
            // 执行业务
        } else {
            return "error,请稍后再试";
        }
        return "ok";
    }

    @ResponseBody
    @GetMapping("/go")
    public String go() {
        RSemaphore park = redisson.getSemaphore("park");
        // 释放一个车位
        park.release();
        return "ok";
    }


}
